<template>
  <div class="global-state-demo">
    <h3>全局状态演示</h3>
    
    <!-- 显示主应用传递的数据 -->
    <div class="main-app-data" v-if="$mainAppData">
      <h4>来自主应用的数据：</h4>
      <p>标题：{{ $mainAppData.title }}</p>
      <p>时间戳：{{ $mainAppData.timestamp }}</p>
    </div>

    <!-- 显示全局状态 -->
    <div class="global-state">
      <h4>全局状态：</h4>
      <p>用户名：{{ globalState.user.name }}</p>
      <p>角色：{{ globalState.user.role }}</p>
      <p>主题：{{ globalState.theme }}</p>
    </div>

    <!-- 操作按钮 -->
    <div class="actions">
      <button @click="updateGlobalState">更新全局状态</button>
      <button @click="sendMessageToMain">发送消息到主应用</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GlobalStateDemo',
  data() {
    return {
      globalState: {
        user: {
          name: '',
          role: ''
        },
        theme: ''
      }
    }
  },
  mounted() {
    // 在 mounted 钩子中获取全局状态
    if (window.__POWERED_BY_QIANKUN__) {
      // 从 Vue 实例的 $root 中获取 props
      const props = this.$root.$props
      if (props && props.getGlobalState) {
        this.globalState = props.getGlobalState()
      }
    }
  },
  methods: {
    // 更新全局状态
    updateGlobalState() {
      if (window.__POWERED_BY_QIANKUN__) {
        const props = this.$root.$props
        if (props && props.setGlobalState) {
          props.setGlobalState({
            user: {
              name: '子应用1用户-' + Date.now(),
              role: 'user'
            },
            theme: this.globalState.theme === 'light' ? 'dark' : 'light'
          })
        }
      }
    },
    // 发送消息到主应用
    sendMessageToMain() {
      if (this.$mainAppMethods && this.$mainAppMethods.showMessage) {
        this.$mainAppMethods.showMessage('来自子应用1的消息：' + Date.now())
      }
    }
  }
}
</script>

<style scoped>
.global-state-demo {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin: 20px;
}

.main-app-data,
.global-state {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.actions {
  display: flex;
  gap: 10px;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style> 